package com.ems.sys.config;

import com.ems.sys.service.impl.UserDataServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;



@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true,jsr250Enabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDataServiceImpl userDataService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        //设置不拦截首页登录页以及静态资源
        http.cors();//启用跨域
        http.csrf().disable();//关闭跨站攻击
        http.authorizeRequests()
                .antMatchers("/captcha").permitAll()
                .antMatchers("/hello","/login.html","/login_error.html").permitAll()
                .anyRequest().authenticated()
//                .antMatchers("http://localhost:8080/").permitAll()
                .and()
                .formLogin()
                //指定登录页的路径
                .loginPage("/hello")
                //指定自定义form表单请求的路径
                .loginProcessingUrl("/authentication/form")
                .failureUrl("/login_error")
                .defaultSuccessUrl("http://localhost:8090/main")
                .permitAll();
        http.logout().logoutUrl("/sys/logout").logoutSuccessUrl("/hello");


    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userDataService).passwordEncoder(encoder);
    }
    //开启不需要安全密码
    @Bean
    NoOpPasswordEncoder noOpPasswordEncoder(){
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**","/js/**","/img/**");
        super.configure(web);
    }
}
